package com.clouddot.baipai.ui.fragment.H;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.clouddot.baipai.R;
import com.clouddot.baipai.component.DaggerIScanFaceFragmentComponent;
import com.clouddot.baipai.contract.IScanFaceFragmentContract;
import com.clouddot.baipai.http.entity.response.postPhotoResponse;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.module.ScanFaceFragmentModule;
import com.clouddot.baipai.ui.activity.H_UMainActivity;
import com.clouddot.baipai.util.ThreadPool.ThreadPool;
import com.clouddot.baipai.util.Toast.ToastUtil;
import com.clouddot.baipai.util.viewUtil.Preview.CameraPreview;

import org.wxy.sdk.base.IBasePresenter;
import org.wxy.sdk.base.impl.BaseFragment;

import javax.inject.Inject;

import butterknife.BindView;


/**
 * Created by wxy on 2018/8/23.
 * 横版班牌USB人脸识别的主页面
 */

public class H_UScanFaceFrgment extends BaseFragment implements IScanFaceFragmentContract.IView {

    private boolean isRunning = false;
    private H_UMainActivity activity;
    private Camera mCamera;
    private CameraPreview mPreview;
    private boolean isFragment = false;

    @Inject
    IScanFaceFragmentContract.IPresenter mPresenter;

    @BindView(R.id.camera_preview)
    FrameLayout mCameralayout;
    @BindView(R.id.takePhoto)
    RelativeLayout mTakePictureBtn;



    @Override
    public IBasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    protected View inflateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
        return inflater.inflate(R.layout.h_fragment_scanfacefg, null);
    }

    @Override
    protected void initViews() {
        activity = (H_UMainActivity) getActivity();
        DaggerIScanFaceFragmentComponent.builder().scanFaceFragmentModule(new ScanFaceFragmentModule(this)).build().inject(this);
        if (!checkCameraHardware(getActivity())) {
            ToastUtil.showToast(getActivity(), "相机不支持", Toast.LENGTH_SHORT);
        } else {
            openCamera();
        }
    }



    @Override
    protected void initVariables() {

        mTakePictureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                H_UMainActivity.backTime = Env.getAppContext().backToMainTime * 60;

                if(!isRunning){
                    isRunning = true;
                    mCamera.takePicture(null, null, mPictureCallback);

//                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.demo);
//                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//
//                    bitmap.compress(Bitmap.CompressFormat.JPEG,90,outputStream );
//
//                    byte[] imagebyte = outputStream.toByteArray();
//
//                    photo = Base64.encodeToString(imagebyte, 0, imagebyte.length, Base64.DEFAULT);
//
//                    runThreadAction();
                }else{
                    ToastUtil.showToast(activity,"正在识别，不用再点击拍照按钮了");
                }
            }
        });


    }

    @Override
    protected void loadData() {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            isFragment = false;
            if (!checkCameraHardware(getActivity())) {
                ToastUtil.showToast(getActivity(), "相机不支持", Toast.LENGTH_SHORT);
            } else {
                openCamera();
            }
        }else{
            isRunning = false;
            isFragment = true;
            releaseCamera();
        }
    }

    @Override
    public void success(int flag, Object object) {
            if (flag == 2) {
                ToastUtil.showToast(getActivity(), "识别通过");
                activity.replacePersion();
                isRunning = false;
            } else if (flag == 1) {
                postPhotoResponse response = (postPhotoResponse) object;
                Env.info(response.idno);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = response.idno;
                handler.sendMessage(msg);
            }
    }

    @Override
    public void fail(int flag, String errMsg) {
        handler.sendEmptyMessage(2);
        ToastUtil.showToast(getActivity(), errMsg);
        isRunning = false;
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mPresenter.login(msg.obj + "");
                    break;
                case 2:
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if(!isFragment) {
                                ToastUtil.showToast(getActivity(), "请对准摄像头");
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        mTakePictureBtn.performClick();
                                    }
                                }, 1000);
                            }
                        }
                    },3000);

                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 开始预览相机
     */
    @SuppressLint("ClickableViewAccessibility")
    public void openCamera() {
        if (mCamera == null) {
            ThreadPool.getInstance().execute(new Runnable() {
                @Override
                public void run() {
                    mCamera = getCameraInstance();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mPreview = new CameraPreview(getActivity(), mCamera);
//                            mPreview.setRotation(180);
                            mCameralayout.addView(mPreview);
                        }
                    });
                    handler.sendEmptyMessage(2);
                }
            });
        }else{
            mPreview = new CameraPreview(getActivity(), mCamera);
            mCameralayout.addView(mPreview);
        }
    }

    /**
     * // 释放相机
     */
    public void releaseCamera() {
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    /**
     * 判断相机是否支持
     *
     * @param context
     * @return
     */
    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取相机
     *
     * @return
     */
    public static Camera getCameraInstance() {
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return c;
    }

    private String photo;
    /**
     * 拍照回调
     */
    private Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(final byte[] data, Camera camera) {

            photo = Base64.encodeToString(data, 0, data.length, Base64.DEFAULT);
            mPresenter.scanFace(photo,"jpeg", "1", "1");

        }
    };

}
